<?php

namespace app\api\controller\sign;

use app\api\controller\Controller;

use app\api\service\User;

class Sign extends Controller
{
    /**签到
     * @return
     */
    function sign()
    {
        $model = new \app\api\model\sign\Sign();
        $user=$this->getUser();
        if (!$model->sign($user['user_id'])) {
            return $this->renderError($model->getError());
        }
        return $this->renderSuccess([],'签到成功');
    }

    public function checkSign(){
        // 当前用户信息
        $user = $this->getUser(false);
        if ($user){
            $sign = new \app\api\model\sign\Sign();
            $is_today = $sign->where('user_id', $user['user_id'])->where('last_sign_time', '>=', strtotime(date('Y-m-d')))
                ->where('last_sign_time', '<=', strtotime(date('Y-m-d 23:59:59')))
                ->find();

            $is_today = $is_today ? 1 : 0;
        }else{
            $is_today = 0;
        }
        return $this->renderSuccess(compact('is_today'));
    }


    /**签到首页
     * @return
     * @throws \cores\exception\BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function index()
    {
        $sign = new \app\api\model\sign\Sign();
        $month_first_day = date('Y-m-01', strtotime(date("Y-m-d")));
        $month_last_day = date('Y-m-d', strtotime("$month_first_day +1 month -1 day"));

        $user = $this->getUser();
        $daylist = $sign->dayList(time(), $user['user_id'], 7);

        //本月签到最新记录
        $record = $sign->where('user_id', $user['user_id'])
            ->where('last_sign_time', '>=', strtotime($month_first_day))
            ->where('last_sign_time', '<=', strtotime($month_last_day) - 1)
            ->order(['last_sign_time' => 'desc'])->find();

        $lianxu = $record ? $record['lianxu_times'] : 0;
        $jifen = $user['points'];

        $is_today = $sign->where('user_id', $user['user_id'])->where('last_sign_time', '>=', strtotime(date('Y-m-d')))
            ->where('last_sign_time', '<=', strtotime(date('Y-m-d 23:59:59')))
            ->find();

        $is_today = $is_today ? 1 : 0;

        $list = $sign->where('user_id', $user['user_id'])
            ->where('last_sign_time', '>=', strtotime($month_first_day))
            ->where('last_sign_time', '<=', strtotime($month_last_day) - 1)->column('last_sign_time');

        $list = array_map(function ($item) {
            return date('Y-m-d', $item);
        }, $list);


        return $this->renderSuccess(compact('lianxu', 'jifen', 'daylist', 'is_today', 'list'));
    }
}